package org.lds.ers.client;

import org.lds.ers.client.model.LoginInfo;
import org.lds.ers.client.widgets.MainForm;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * 整個程式的進入點
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class ERSC implements EntryPoint {
	
	private LoginInfo loginInfo = null;
	private Label loginLabel = new Label("請用您新竹支聯會 的 Google Apps ( XXX@ldshc.org )的帳號登入系統！");
	private Anchor signInLink = new Anchor("按這裡登入系統");
	private VerticalPanel loginPanel = new VerticalPanel();

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
			
			public void onFailure(Throwable caught) {
				Window.alert("登入失敗");
			}

			public void onSuccess(LoginInfo result) {
				loginInfo = result ;
				MyInfo.set(result);
				if (loginInfo.isLoggedIn()) {
					RootPanel.get().add(MainForm.getInstance());
				} else {
					loadLogin();
				}
			}
		});
	}
	
    private void loadLogin() {
	    // Assemble login panel.
	    signInLink.setHref(loginInfo.getLoginUrl());
	    loginPanel.add(loginLabel);
	    loginPanel.add(signInLink);
	    RootPanel.get().clear();
	    RootPanel.get().add(loginPanel);
	}

}
